#!/usr/bin/env python
#coding:utf-8
import pkg_resources
import os,sys
import web

PATH = os.path.dirname(os.path.realpath(sys.argv[0]))
sys.path.append(PATH)

from include import common
from include import bbs
from include import user
from include import util
from include.feeds import pushfeed
import re
import time,calendar
import random,hashlib,zlib
import socket,json
from collections import defaultdict
from operator import itemgetter


web.config.debug = False

ECAT = {
	'anime':'动画',
	'music':'音乐',
	'game':'游戏',
	'ent':'娱乐',
	'zj':'番影',
	'art':'文章',
	'hidden':'hidden',
}
MCAT = {'anime':'/list/anime/1',
       'music':'/list/music/1',
       'game':'/list/game/1',
       'ent':'/list/ent/1',
       'zj':'/list/zj/1',
       'art':'/list/art/1',}
M2CAT = {'动画':'/list/anime/1',
       '音乐':'/list/music/1',
       '游戏':'/list/game/1',
       '娱乐':'/list/ent/1',
       '番影':'/list/zj/1',
       '專輯':'/list/zj/1',
       '文章':'/list/art/1',}

urls = (
	'/checkpri/(.*)','checkpri',
	'/idr/(.*)','id',
	'/listr/(.*)', 'list',
	'/comment/(.*)', 'comment',
	'/click/(.*)','click',
	'/subtitler/(.*)','subtitle',
	'/playlist/(.*)','playlist',
	'/indexr/(.*)','index',
	'/search/(.*)','search',
	'/rankr/(.*)','rank',
	'/userrankr/(.*)','userrank',
	'/about/(.*)','about',
	'/login/(.*)','login',
	'/checklogin/(.*)','checklogin',
	'/logout/(.*)','logout',
	'/register/(.*)','register',
	'/apikey/(.*)','apikey',
	'/banlist/(.*)','banlist',
	'/online/(.*)','online',
	'/bbs',bbs.app_bbs,
	'/user',user.app_user,
	'/mark/(.*)','mark',
	'/review/(.*)','review',
	'/admin/(.*)','admin',
)

searchdb = web.database(dbn='sqlite', db=PATH+'/searchdb.db3')

app = web.application(urls, globals())

tpls = util.tpls

def getuid(c=None):
	if not c:
		c = common.getdb().cursor()
	uid = web.cookies().get('uid')
	md5 = web.cookies().get('md5')
	if uid and md5:
		c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
		x = c.fetchone()
		if x and x[0]==md5:
			uid = int(uid)
		else:
			uid = 0
	return uid

class index:
	def GET(self,idx):
		c = common.getdb().cursor()
		try:
			# face pictures
			c.execute('''select id,title,osite
					from ac_threads left join ac_stats using(id) 
					where visible=1 and date>%s
					order by (avclicks) desc limit %s''',
					(common.last_epoch(300),30))
			faces = []
			allfaces = []
			for x in c.fetchall():
				id,title,osite = x
				sid = str(id)
				title = title.decode('utf-8')
				fname = PATH + '/thumbs/%s/%s/%s.jpg' % (sid[:1],sid[1:3],sid)
				if os.path.exists(fname):
					if osite != 'bilibili':
						faces.append( [ id,title ] )
					allfaces.append( [id,title] )
			random.shuffle(faces)
			random.shuffle(allfaces)
			faces = [faces[:8]]
			allfaces = [allfaces[:8]]
			for category in ['动画','音乐','游戏','娱乐','番影']:
				c.execute('''select id,title,osite from ac_threads left join ac_stats using(id)
							where visible=1 and category=%s and date>%s
							order by (clicks+avclicks) desc limit %s''',
							(category,common.last_epoch(300),30))
				tempfaces = []
				tempallfaces = []
				for x in c.fetchall():
					id,title,osite = x
					sid = str(id)
					title = title.decode('utf-8')
					fname = PATH + '/thumbs/%s/%s/%s.jpg' % (sid[:1],sid[1:3],sid)
					if os.path.exists(fname):
						if osite != 'bilibili':
							tempfaces.append( [ id,title ] )
						tempallfaces.append( [ id,title ] )
				random.shuffle(tempfaces)
				random.shuffle(tempallfaces)
				faces.append(tempfaces[:8])
				allfaces.append(tempallfaces[:8])
			# recents
			c.execute('''SELECT ac_threads.id,title,abstract,ac_threads.date,
				clicks+avclicks,comments+avcomments,ac_stats.subs,uid,nickname,osite
				FROM ((ac_threads LEFT JOIN ac_stats USING (id)) LEFT JOIN ac_upers USING (uid))
					RIGHT JOIN (SELECT DISTINCT(id) from ac_posts ORDER BY pid DESC LIMIT 40) 
					as ids ON ids.id=ac_threads.id
                 WHERE category != "文章" and category != "番影" and visible = 1
				''')
			recents = []
			allrecents = []
			for x in c.fetchall():
				try:
					sid = str(x[0])
					fname = PATH + '/thumbs/%s/%s/%s.jpg' % (sid[:1],sid[1:3],sid)
					if not os.path.exists(fname):
						continue
					if x[7]<100:
						x[7] = '%03d' % x[7]
					if x[9] != 'bilibili':
						recents.append([
							x[0],x[1].decode('utf-8'),x[2].decode('utf-8'),
							common.int2timestr(x[3],'%Y-%m-%d'),x[4],x[5],x[6],x[7],x[8].decode('utf-8')
						])
					allrecents.append([
						x[0],x[1].decode('utf-8'),x[2].decode('utf-8'),
						common.int2timestr(x[3],'%Y-%m-%d'),x[4],x[5],x[6],x[7],x[8].decode('utf-8')
					])
				except:
					continue
			recents = recents[:8]
			allrecents = allrecents[:8]
			c.execute('''SELECT id,title,osite FROM ac_threads 
       	          WHERE visible = 1
       	          ORDER BY id DESC LIMIT %s''',(common.PERUPDATES,) )
			m = c.fetchall()
			updates = [ [x[0],x[1].decode('utf-8')[:20]] for x in m if x[1] and x[2] != 'bilibili' ]
			allupdates = [ [x[0],x[1].decode('utf-8')[:20]] for x in m if x[1] ]
			html = tpls.get_template('index2.html').render(recents=recents,updates=updates,faces=faces)
			allhtml = tpls.get_template('index2.html').render(recents=allrecents,updates=allupdates,faces=allfaces)
			open( PATH+'/data/index.html','wb').write( html )
			open( PATH+'/data/allindex.html','wb').write( allhtml )
			return html
		except Exception as what:
			return util.error_page(u'解析出错：%s'%repr(what).replace('"',"'"))
			

class list:
	def GET(self,catpage):
		try:
			cat,page = catpage.split('/')
			page = int(page)	
			cate = cat
			cat = ECAT[cat]
		except:
			return util.error_page('invalid request')
		c = common.getdb().cursor()
		# hidden zone
		if cat == 'hidden':
			uid = web.cookies().get('uid')
			if not uid:
				return util.error_page(u'您没有权限访问本区')
			try:
				cat = u'里区'
				catnav = '/list/hidden/1'
				c.execute( 'SELECT count(*) FROM ac_threads WHERE visible=0' )
				total = c.fetchone()[0]
				# entries
				if page < 10:
					c.execute( '''SELECT id,title,ac_threads.date,nickname,abstract,category,
							clicks+avclicks,comments+avcomments,ac_stats.subs,osite,ac_upers.uid,aliasid
	                      FROM (ac_threads LEFT JOIN ac_stats USING (id)) LEFT JOIN ac_upers USING (uid)
   	    	               WHERE visible=0 ORDER BY date DESC LIMIT %s,%s''', ((page-1)*common.PERPAGE,common.PERPAGE) )
					entries = []
					for x in c.fetchall():
						try:
							entries.append( [x[0],x[1].decode('utf-8'),common.int2timestr(x[2],'%Y-%m-%d'),x[3].decode('utf-8'),x[4].decode('utf-8'),x[5].decode('utf-8'),x[6],x[7],x[8],x[9],x[10],x[11]] )
						except:
							entries.append( [x[0],'title too long',common.int2timestr(x[2],'%Y-%m-%d'),x[3].decode('utf-8'),x[4].decode('utf-8'),x[5].decode('utf-8'),x[6],x[7],x[8],x[9],x[10],x[11]] )
				else: #后面的列表就用sqlite来做，否则这速度不能忍
					data = searchdb.select('searchdb',order='date desc',where='category like "%s%%"'%cat,
						limit=common.PERPAGE,offset=(page-1)*common.PERPAGE)
					entries = []
					for x in data:
						entries.append( [x.id, x.title.decode('utf-8'),common.int2timestr(x.date,'%Y-%m-%d'),x.nickname.decode('utf-8'),x.abstract.decode('utf-8'),x.category.decode('utf-8'),x.clicks,x.comments,x.subs,x.osite,x.uid,x.aliasid] )
				#top
				c.execute( '''SELECT id,title,clicks+avclicks
    	                  FROM ac_stats INNER JOIN ac_threads USING (id)
       	               WHERE visible=0 and date>%s
       	               ORDER BY avclicks DESC LIMIT %s''', (common.lastweek_epoch(),common.PERTOP) )
				tops = []
				for x in c.fetchall():
					tops.append( [ x[0],x[1].decode('utf-8'),x[2] ] )
				#nav
				cur,records,pages,navs,prev,next,last = util.generate_navs(page,total,common.PERPAGE)
				listfile = PATH + '/data/list/hidden/%s.html' % str(page)
				common.ensure_dir( listfile )
				html = tpls.get_template('list2.html').render(catnav=catnav,cat=cat,entries=entries,pages=pages,records=records,cur=cur,prev=prev,next=next,last=last,navs=navs,tops=tops)
				#do not make cache
				#open(listfile,'wb').write(html)
				return html
			except Exception as what:
				return util.error_page(u'%s'%repr(what).replace('"',"'"))
		# normal zones
		c.execute( 'SELECT count(*) FROM ac_threads WHERE category=%s and visible=%s',(cat,1) )
		total = c.fetchone()[0] # total number of current category
		#entries
		try:
			if page < 10:
				c.execute( '''SELECT id,title,ac_threads.date,nickname,abstract,category,
						clicks+avclicks,comments+avcomments,ac_stats.subs,osite,ac_upers.uid,aliasid
                      FROM (ac_threads LEFT JOIN ac_stats USING (id)) LEFT JOIN ac_upers USING (uid)
                      WHERE category=%s and visible=%s ORDER BY ac_threads.date DESC LIMIT %s,%s''', 
						(cat,1,(page-1)*common.PERPAGE,common.PERPAGE) )
				entries = []
				for x in c.fetchall():
					try:
						entries.append( [x[0],x[1].decode('utf-8'),common.int2timestr(x[2],'%Y-%m-%d'),x[3].decode('utf-8'),x[4].decode('utf-8'),x[5].decode('utf-8'),x[6],x[7],x[8],x[9],x[10],x[11]] )
					except:
						pass
			else: #后面的列表就用sqlite来做，否则这速度不能忍
				data = searchdb.select('searchdb',where='category like "%s%%"'%cat,order='date desc',
					limit=common.PERPAGE,offset=(page-1)*common.PERPAGE)
				entries = []
				for x in data:
					entries.append( [x.id, x.title,common.int2timestr(x.date,'%Y-%m-%d'),x.nickname,x.abstract,x.category,x.clicks,x.comments,x.subs,x.osite,x.uid,x.aliasid] )
		except Exception as what:
			return util.error_page(u"渲染失败:%s"%what.__str__().replace('"',"'"))
		#tops
		if cat == '番影':
			c.execute( '''SELECT id,title,clicks+avclicks
                      FROM ac_stats INNER JOIN ac_threads USING (id)
                      WHERE category != %s and visible=%s and date>%s
                      ORDER BY clicks DESC LIMIT %s''', 
                      ("文章",1,common.lastweek_epoch(),common.PERTOP) )
			tops = []
			for x in c.fetchall():
				tops.append( [ x[0],x[1].decode('utf-8'),x[2] ] )
		else:
			c.execute( '''SELECT id,title,clicks+avclicks
                      FROM ac_stats INNER JOIN ac_threads USING (id)
                      WHERE category=%s and visible=%s and date>%s
                      ORDER BY clicks DESC LIMIT %s''', (cat,1,common.lastweek_epoch(),common.PERTOP) )
			tops = []
			for x in c.fetchall():
				tops.append( [ x[0],x[1].decode('utf-8'),x[2] ] )
		
	#	generate_page
		cur,records,pages,navs,prev,next,last = util.generate_navs(page,total,common.PERPAGE)
		catnav = MCAT[cate]
		cat = cat.decode('utf-8')
		listfile = PATH + '/data/list/%s/%s.html' % (cate,str(page))
		common.ensure_dir( listfile )
		html = tpls.get_template('list2.html').render(catnav=catnav,cat=cat,entries=entries,pages=pages,records=records,cur=cur,prev=prev,next=next,last=last,navs=navs,tops=tops)
		open(listfile,'wb').write( html )
		return html
		
class id:
	def GET(self,id):
		partid = id
		id = int(float(id))
		c = common.getdb().cursor()
		try:
			c.execute('''SELECT title,ac_threads.date,nickname,category,url,part,parts,content,
					clicks+avclicks,abstract,osite,visible,uid
                 FROM ((ac_threads LEFT JOIN ac_upers USING (uid)) LEFT JOIN ac_videos USING (id)) 
                 LEFT JOIN ac_stats USING (id)
                 WHERE id=%s''', (id,))
			r = c.fetchone()
			if not r:
				return util.error_page('id not found')
			if not r[0]:
				return util.error_page('no title')
			# 里区 并且 未登录
			if (r[11]!=1) and (not web.cookies().get('uid')):
				return util.error_page(u"对不起，您没有权限访问本资源")
			visible = r[11]
			title = r[0].decode('utf-8')
			date = common.int2timestr( r[1], '%y-%m-%d %H:%M:%S' )
			username = r[2].decode('utf-8')
			cat = r[3].decode('utf-8')
			catnav = M2CAT[cat.encode('utf-8')]
			acurl = r[4]
			acip = common.AC_IP
			url = r[4]
			part = r[5]
			if not part:
				return util.error_page('no part')
			parts_temp = r[6].decode('utf-8').split('`')
			parts = []
			try:
				for i in range(len(parts_temp)/2):
					parts.append( [float(parts_temp[i*2]),parts_temp[i*2+1]] )
			except:
				pass
			try:
				content = r[7].decode('utf-8')
			except:
				return util.error_page( 'decode error' )
			clicks = r[8]
			abstract = r[9].decode('utf-8')
			osite = r[10]
			uid = r[12]
	
			if cat == '文章'.decode('utf-8'):
				html = tpls.get_template('article.html').render(id=id,title=title,date=date,username=username,cat=cat,catnav=catnav,url=url,parts=parts,content=content,clicks=clicks,abstract=abstract,acurl=acurl,acip=acip,uid=uid,partid=partid)
				idfile = PATH + '/data/id/%s/%s/%s.html' % (str(id)[:1],str(id)[1:3],str(id))
				common.ensure_dir(idfile)
				open(idfile,'wb').write(html)		
				return html
	
			# face pictures
			try:
				ok = False
				while not ok:
					c.execute('''select ac_threads.id,title 
						from (ac_threads left join ac_stats using(id))
							join (select floor(rand()*max(id)-100) as id from ac_threads) as x on (ac_threads.id) 
						where visible=1 and category=%s and clicks+avclicks>1000 and ac_threads.id>x.id
						limit %s''',
						(cat.encode('utf-8'),100))
					faces = []
					for x in c.fetchall():
						id2,ttl = x
						sid = str(id2)
						ttl = ttl.decode('utf-8')[:10]
						fname = PATH + '/thumbs/%s/%s/%s.jpg' % (sid[:1],sid[1:3],sid)
						if os.path.exists(fname):
							faces.append( [ id2,ttl ] )
					try:
						faces = random.sample(faces,8)
						ok = True
					except:
						ok = False
			except Exception as what:
				return util.error_page(u'缩略图错:%s'%repr(what).replace('"',"'"))

			curpart = float(partid)
			c.execute('select flashvars,vvid,content from ac_parts where partid=%s',(curpart,))
			r2 = c.fetchone()
			if not r2:
				return util.error_page('part not found')
			flashvars = r2[0].decode('gbk')
			vvid = r2[1]
			try:
				pcontent = r2[2].decode('utf-8')
			except:
				pcontent = ''
			idfile = PATH + '/data/id/%s/%s/%s.html' % (str(id)[:1],str(id)[1:3],str(curpart))
			common.ensure_dir(idfile)
			xmlname = '/subtitle/%s' % str(curpart)
			try:
				if visible == 1:
					html = tpls.get_template('video.html').render(flashvars=flashvars,vvid=vvid,curpart=curpart,title=title,abstract=abstract,catnav=catnav,cat=cat,date=date,username=username,parts=parts,xmlname=xmlname,content=content,id=id,clicks=clicks,partid=partid,acip=acip,acurl=acurl,osite=osite,uid=uid,pcontent=pcontent,faces=faces)
				else:
					html = tpls.get_template('hvideo.html').render(flashvars=flashvars,vvid=vvid,curpart=curpart,title=title,abstract=abstract,catnav=catnav,cat=cat,date=date,username=username,parts=parts,xmlname=xmlname,content=content,id=id,clicks=clicks,partid=partid,acip=acip,acurl=acurl,osite=osite,uid=uid,pcontent=pcontent,faces=faces)
			except Exception as what:
				return util.error_page(what.__str__())
			if r[11]:
				open(idfile,'wb').write(html)
			return html
		except Exception as what:
			return util.error_page(u'生成出错:%s'%repr(what).replace('"',"'"))
	
class comment:		
	def GET(self, id):
		if not id:
			return ''
		if '/' not in id:
			id += '/1'
		id,curpage = id.split('/')
		try:
			id = int(id)
			curpage = int(curpage)
		except:
			return ''
		c = common.getdb().cursor()
		c.execute( '''SELECT title FROM ac_threads WHERE id=%s''',(id,) )
		title = c.fetchone()
		if title:
			title = title[0].decode('utf-8')
		else:
			title = ''
		uid = web.cookies().get('uid')
		if uid:
			uid = int(uid)
			c.execute( 'select nickname from ac_upers where uid=%s', (uid,) )
			nickname = c.fetchone()
			if nickname:
				nickname = nickname[0].decode('utf-8')
			else:
				nickname = '游客'.decode('utf-8')
		else:
			nickname = '游客'.decode('utf-8')
		# check if alias exists
		c.execute('select aliasid from ac_threads where id=%s',(id,))
		aliasid = c.fetchone()[0]
		if aliasid:
			c.execute( 'select count(*) from ac_posts where id=%s or id=%s',(id,aliasid) )
		else:
			c.execute( 'select count(*) from ac_posts where id=%s',(id,) )
		floors = c.fetchone()
		if not floors:
			floors = 0
			lastpage = 1
			pages = [1]
			cmts = []
		else:
			floors = floors[0]
			lastpage = (floors-1)/50+1
			if curpage<=4:
				pages = range(1,min(lastpage+1,8))
			else:
				pages = range(curpage-3,min(lastpage+1,curpage+4))
			if aliasid:
				c.execute( '''SELECT nickname,ac_posts.date,content,uid
					  FROM ac_posts LEFT JOIN ac_upers USING (uid)
					  WHERE id=%s or id=%s ORDER BY ac_posts.date DESC LIMIT %s,%s''',
					  (id,aliasid,50*(curpage-1),50) )
			else:
				c.execute( '''SELECT nickname,ac_posts.date,content,uid
					  FROM ac_posts LEFT JOIN ac_upers USING (uid)
					  WHERE id=%s ORDER BY ac_posts.date DESC LIMIT %s,%s''',
					  (id,50*(curpage-1),50) )
			cs = c.fetchall()
			try:
				cmts = []
				for x in cs:
					try:
						cmts.append( [ 0,x[0].decode('utf-8'),x[1],x[2].decode('utf-8'),x[3] ] )
					except:
						pass
			except Exception as what:
				return what.__str__()
			length = len(cmts)
			for i in xrange(length):
				cmts[i][0] = floors - i - (curpage-1)*50
				cmts[i][2] = common.int2timestr( cmts[i][2], '%Y-%m-%d %H:%M:%S' )
		return tpls.get_template('feedback.html').render(id=id,title=title,curpage=curpage,lastpage=lastpage,pages=pages,cmts=cmts,nickname=nickname)
	def POST(self,arg):
		i = web.input()
		uid = web.cookies().get('uid')
		md5 = web.cookies().get('md5')
		if uid and md5:
			c = common.getdb().cursor()
			c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
			x = c.fetchone()
			if x and x[0]==md5 and i.msg and i.id:
				try:
					c.execute('''insert into ac_posts (uid,date,content,id) 
						values (%s,%s,%s,%s)''',
						(int(uid),int(calendar.timegm(time.gmtime()))+3600*8,
							i.msg.replace('\n','<br>').encode('utf-8'),int(i.id)) )
					c.execute('update ac_stats set avcomments = avcomments+1 where id=%s',(int(i.id),))
					if int(uid):
						c.execute('update ac_upers set posts = posts+1 where uid=%s',(int(uid),))
						# 推送feed
						pushfeed( int(uid),'评论',i.msg[:20].encode('utf-8'),c=c,id=int(i.id ) )
					html = tpls.get_template('cmtjump.html').render(id=i.id)
					return html
					#return jump_page(u'发表成功','/id/%s.001'%i.id)
				except Exception as what:
					return util.error_page(what.__str__(),'/id/%s.001'%i.id)
		return util.error_page(u'请登录先','/id/%s.001'%i.id)

class subtitle:
	def GET(self,partid):
		c = common.getdb().cursor()
		try:
			partid=float(partid)
		except:
			return util.error_page('invalid partid')
		# see if an alias exists
		id = int(partid)
		c.execute('select aliasid from ac_threads where id=%s',(id,))
		aliasid = c.fetchone()[0]
		if aliasid:
			aliasid = partid - id + aliasid
			c.execute('''select time,txt,date,mode,color,fontsize
					from ac_subs_10p where partid=%s or partid=%s''', (partid,aliasid))
		else:
			c.execute('''select time,txt,date,mode,color,fontsize
					from ac_subs_10p where partid=%s''', (partid,))
		
		header = '''<?xml version="1.0" encoding="utf-8"?>
<information>
'''
		footer = '''</information>'''
		xml = header
		for d in c.fetchall():
			xml+='''  <data>
    <playTime>%s</playTime>
    <message fontsize="%s" color="%s" mode="%s">%s</message>
    <times>%s</times>
  </data>
''' % (d[0],d[5],d[4],d[3],d[1],common.int2timestr(d[2]))
		xml += footer
		web.header('Content-Type', 'text/xml')
		pid = str(partid)
		xmlfile = PATH + '/data/subtitle/%s/%s/%s.xml' % (pid[:1],pid[1:3],pid)
		#common.ensure_dir(xmlfile)
		#open( xmlfile,'wb' ).write(xml)
		return xml
	def POST(self,anything):
		i = web.input()
		c = common.getdb().cursor()
		# proxy is used in apache mod_wsgi
		ip = web.ctx.environ['HTTP_X_FORWARDED_FOR'] 
		ipv4 = util.str2ip(ip)
		# verify user identity
		uid = web.cookies().get('uid')
		md5 = web.cookies().get('md5')
		if uid and md5:
			c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
			x = c.fetchone()
			if x and x[0]==md5:
				uid = int(uid)
			else:
				uid = 0
		else:
			uid = 0
		# if is a delete request:
		try:
			if uid == 0 and i.type != 'add':
				return 'please login first'
			if i.type=="delete" and uid:
				partid = float(i.pid)
				#test if you're the uploader/admin of this video
				c.execute('select uid from ac_threads where id=%s',(int(partid),))
				uuid = c.fetchone()[0]
				if uuid != uid:
					c.execute('select mask from ac_upers where uid=%s',(uid,))
					mask = c.fetchone()[0]
					if not (mask & common.UP_SUBADMIN):
						return 'only uploader and admins can delete subtitles'
				mode = int(i.mode)
				date = common.timestr2int(i.date)
				if mode==1: # delete single msg
					c.execute('''delete from ac_subs_10p where partid=%s and date=%s''',
						(partid,date) )
					return 'single msg deleted'
				else:
					c.execute('''select txt,ipv4 from ac_subs_10p where partid=%s and date=%s''',
						(partid,date) )
					x = c.fetchone()
					if x:
						txt = x[0]
						ipv4 = x[1]
						# anyway, delete the msg first
						c.execute('''delete from ac_subs_10p where partid=%s and date=%s''',
							(partid,date) )
						if mode==2: # delete same msgs
							c.execute('''delete from ac_subs_10p where partid=%s and txt=%s''',
								(partid,txt) );	
							return 'same msg deleted'
						elif mode==3 and ipv4: # delete by ipv4
							c.execute('''delete from ac_subs_10p where partid=%s and ipv4=%s''',
								(partid,ipv4) );
							return 'same ipv4 deleted'
						else:
							return 'only single msg deleted'
					else:
						return 'already deleted'
		except Exception as what:
			return what.__str__()
		try:
			checksum = zlib.adler32(hashlib.sha224(i.pid+i.date).digest())
			if checksum == int(i.checksum):
				# before perform the insertion, let's see if it is a spam
				c.execute('insert into ac_visitlog (ipv4,time) values (%s,NOW())',(ipv4,))
				c.execute('delete from ac_visitlog where time<NOW()-INTERVAL 5 MINUTE')
				c.execute('select count(*) from ac_visitlog where ipv4=%s',(ipv4,))
				count = c.fetchone()[0]
				if count > common.SPAM_COUNT_IN_5MIN:
					c.execute('''replace into ac_banlist (ipv4,due) values 
						(%s,NOW()+INTERVAL 1 DAY)''',	(ipv4,))
				# see if the ip is in banlist and not past due
				c.execute('select due from ac_banlist where ipv4=%s and due>NOW()',(ipv4,))
				if c.fetchone():
					return 'you are in the banlist'
				# now let's insert the subtitle
				c.execute( '''insert into ac_subs_10p 
					(partid,time,txt,date,mode,color,fontsize,uid,ipv4)
					values (%s,%s,%s,%s,%s,%s,%s,%s,%s )
					''', ( float(i.pid), float(i.playTime),i.message.encode('utf-8'),
				common.timestr2int(i.date), int(i.mode), int(i.color),
				int(i.fontsize), uid, ipv4 ) )
				c.execute( ''' update ac_stats set subs = subs + 1 where id = %s ''',(int(float(i.pid)),) )
			else:
				return 'Checksum does not meet'
		except Exception as what:
			return what.__str__()
		return 'comment received'

class playlist:
	def GET(self,partid):
		try:
			partid = float(partid)
		except:
			return util.error_page('invalid partid')
		web.header('Content-Type', 'text/xml')
		c = common.getdb().cursor()
		c.execute( 'select vxml from ac_parts where partid=%s',(partid,) )
		vxml = c.fetchone()[0]
		return vxml



class search:
	def GET(self,q):
		web.header('Content-Type', 'text/html')
		q = q.strip()
		if q[-1] == '+':
			q = q[:-1]
		if '/' in q:
			try:
				page = int(q.rsplit('/',1)[1])
				q = q.rsplit('/',1)[0]
				if '/' in q:
					order = q.rsplit('/',1)[1]
					q = q.rsplit('/',1)[0]
				else:
					order = 'date'
			except:
				return util.error_page('invalid search term')
		else:
			order = 'date'
			page = 1
		# insert into database
		try:
			c = common.getdb().cursor()
			qs = [ (x.encode('utf-8'),) for x in q.split('+') ]
			c.executemany('insert into ac_searches values (%s,NOW())',qs)
		except:
			pass
		where = '(' + 'and'.join([' title like "%'+x+'%" ' for x in q.split('+') if x]) + ')'
		where += ' or ' +  '(' + 'and'.join([' abstract like "%'+x+'%" ' for x in q.split('+')]) + ')'
		where += ' or ' +  '(' + 'and'.join([' nickname like "%'+x+'%" ' for x in q.split('+')]) + ')'
		results = searchdb.select('searchdb',what='id',where=where)
		results = [ x.id for x in results ]
		total = len(results)
		ids = 'id in (' + ','.join( [ str(x) for x in results ] ) + ')'
		results = searchdb.select('searchdb',where=ids,order='%s desc'%order,
			limit=common.PERPAGE2,offset=(page-1)*common.PERPAGE2)
		entries = []
		for x in results:
			entries.append( [x.id,
				util.hightlight( q, x.title ),
				common.int2timestr(x.date,'%Y-%m-%d'),
				util.hightlight( q, x.nickname ),
				util.hightlight( q, x.abstract ),
				x.category,x.clicks,x.comments,x.subs,x.osite,x.uid,x.aliasid] )
		cat = u'搜索结果: %s'%q
		cur,records,pages,navs,prev,next,last = util.generate_navs(page,total,common.PERPAGE2)
		orderdict = { 'date':u'按日期排序','clicks':u'按点击排序',
				'comments':u'按评论排序','subs':u'按弹幕排序' }
		html = tpls.get_template('search2.html').render(q=q,order=order,cat=cat,entries=entries,pages=pages,records=records,cur=cur,prev=prev,next=next,last=last,navs=navs,orderdict=orderdict)
		return html 

class rank:
	def GET(self,ecat):
		request = ecat
		if ecat == '':
			rankfile = PATH + '/data/rank/all/clicks/1.html'
			return open(rankfile,'rb').read()
		if '/' in ecat:
			page = int(ecat.rsplit('/',1)[1])
			ecat = ecat.rsplit('/',1)[0]
			if '/' in ecat:
				order = ecat.rsplit('/',1)[1]
				ecat = ecat.rsplit('/',1)[0]
		else:
			ecat = 'all'
			order = 'clicks'
			page = 1
		catdict = { 'all':u'所有','anime':u'动画','music':u'音乐',
			'ent':u'娱乐','game':u'游戏','zj':u'番影','art':u'文章' }
		orderdict = { 'clicks':u'按点击排序','comments':u'按评论排序','subs':u'按弹幕排序' }
		if ecat == 'all':
			total = searchdb.select('searchdb',what='count(*) as cnt')[0].cnt
			results = searchdb.select('searchdb',order='%s desc'%order,
				limit=common.PERPAGE2,offset=(page-1)*common.PERPAGE2)
		else:
			cat = catdict[ecat].encode('utf-8')
			where = 'category = "%s"' % cat
			total = searchdb.select('searchdb',what='count(*) as cnt',where=where)[0].cnt
			results = searchdb.select('searchdb',order='%s desc'%order,where=where,
				limit=common.PERPAGE2,offset=(page-1)*common.PERPAGE2)
		entries = []
		for x in results:
			entries.append( [x.id,x.title,common.int2timestr(x.date,'%Y-%m-%d'),
				x.nickname,x.abstract,x.category,x.clicks,x.comments,x.subs,x.osite,x.uid,x.aliasid] )
		cur,records,pages,navs,prev,next,last = util.generate_navs(page,total,common.PERPAGE2)
		cat = u'排行榜' # for header title
		html = tpls.get_template('rank2.html').render(cat=cat,ecat=ecat,catdict=catdict,order=order,orderdict=orderdict,entries=entries,pages=pages,records=records,cur=cur,prev=prev,next=next,last=last,navs=navs)
		if request == '':
			request = 'index'
		rankfile = PATH + '/data/rank/%s.html' % request
		common.ensure_dir(rankfile)
		open(rankfile,'wb').write(html)
		return html


class about:
	def GET(self,arg):
		c = common.getdb().cursor()
		try:
			c.execute('select cid,username,date,url,content,parent from gb_cmts order by date asc');
			cmts = []
			count = 0
			for x in c.fetchall():
				try:
					cmts.append([
						x[0],x[1].decode('utf-8'),x[2],x[3],
						util.cite(x[4].decode('utf-8'),x[5],c)
					])
				except:
					pass
				count += 1
			counter = 'about'
			c.execute('select * from ac_counters where counter=%s',(counter,))
			if c.fetchone():
				c.execute('''update ac_counters set clicks = clicks + 1 where counter=%s''',(counter,))
			else:
				c.execute('insert into ac_counters values (%s,1)',(counter,))
			c.execute('select clicks from ac_counters where counter=%s',(counter,))
			views = c.fetchone()[0]
			html = tpls.get_template('about.html').render(cmts=cmts,count=count,views=views)
			return html
		except Exception as what:
			return util.error_page(u'解析出错：%s'%repr(what).replace('"',"'"))
	def POST(self,arg):
		i = web.input() # name,email,url,content,parent_id
		c = common.getdb().cursor()
		if not util.validate_email(i.email):
			return util.error_page('email not valid')
		if not i.name:
			return util.error_page('username must be provided')
		if not i.content:
			return util.error_page('do not leave an empty message')
		i.content = i.content.replace('\n','<br>')
		i.content = i.content.encode('utf-8')
		i.name = i.name.encode('utf-8')
		#return i.content
		c.execute('''insert into gb_cmts (username,email,url,content,parent) values
					(%s,%s,%s,%s,%s)''',(i.name,i.email,i.url,i.content,int(i.parent_id)))
		raise web.seeother('/about/')


class checklogin:
	def GET(self,noarg):
		uid = web.cookies().get('uid')
		md5 = web.cookies().get('md5')
		if uid and md5:
			c = common.getdb().cursor()
			c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
			x = c.fetchone()
			if x and x[0]==md5:
				html = tpls.get_template('checklogin.html').render(nickname=x[1].decode('utf-8'),uid=uid)
				return html
		return '''  <form name="form1" method="POST" action="/login/">
    <table width="310" align="center" cellpadding="0" cellspacing="0" bgcolor="#F5F5F5" class="t1">
      <tr>
        <td colspan="4" height="28">&nbsp;&nbsp;用户名 
          <input size="10" class="in" name="username" type="text">
			&nbsp;密码 <input size="10" class="in" name="password" type="password">
        </td>
      </tr>
      <tr>
	   <td width="4%" height="28"></td>
	   <td width="22%"><input name="imageField" type="image" src="/static/login.gif" width="62" height="19" border="0"/></td>
	   <td width="24%"><a href="/register/"><img src="/static/regs.gif" width="62" height="19" border="0"></a></td>
	  </tr>
    </table>
  </form>
'''
		
class logout:
	def GET(self,noarg):
		web.setcookie('uid','',300,'')
		web.setcookie('md5','',300,'')
		return util.jump_page(u'您已经退出，跳转主页中……')

class login:
	def GET(self,noarg):
		cat = u'用户登录'
		referer = web.ctx.env.get('HTTP_REFERER')
		html = tpls.get_template('login.html').render(cat=cat,referer=referer)
		return html
	def POST(self,noarg):
		i = web.input()
		try:
			ref = i.referer
		except:
			ref = '/'
		c = common.getdb().cursor()
		try:
			try:
				c.execute('select username,salt,md5,uid from ac_upers where username=%s',
					(i.username.encode('utf-8'),))
			except:
				c.execute('select username,salt,md5,uid from ac_upers where username=%s',
					(i.username,))
			x = c.fetchone()
			if not x:
				return util.error_page(u'该用户名不存在，返回首页中……')
			if not x[1]:
				return util.error_page(u'该用户是ac/bili用户，需要激活才能访问……','/activate/')
			md5 = hashlib.md5( i.password + x[1] ).hexdigest()
			if md5 == x[2]:
				#save cookie for 100 days
				web.setcookie('uid', x[3], 8640000, '')
				web.setcookie('md5', x[2], 8640000, '')
				return util.jump_page(u'登录成功，跳转上个访问页面中……',ref)
			else:
				return util.error_page(u'用户名或密码错，返回首页中……')
		except Exception as what:
			return util.error_page(u'解码错误:%s'%repr(what))

class register:
	def GET(self,noarg):
		cat = u"注册新帐号"
		html = tpls.get_template('register.html').render(cat=cat)
		return html
		return util.error_page(u'少女傲娇中')
	def POST(self,noarg):
		ip = web.ctx.environ['HTTP_X_FORWARDED_FOR']
		i = web.input()
		c = common.getdb().cursor()
		if i.dopost == 'checkuser':
			c.execute('select * from ac_upers where username=%s',(i.username.encode('utf-8'),))
			if c.fetchone():
				return '''<font color='red'><b>×用户名已经存在！</b></font>'''
			else:
				return '''<font color='#4E7504'><b>√用户名可以使用</b></font>'''
		if i.dopost == 'checknick':
			c.execute('select * from ac_upers where nickname=%s',(i.nickname.encode('utf-8'),))
			if c.fetchone():
				return '''<font color='red'><b>×用户昵称已经存在！</b></font>'''
			else:
				return '''<font color='#4E7504'><b>√用户昵称可以使用</b></font>'''
		if i.dopost == 'checkmail':
			c.execute('select * from ac_upers where email=%s',(i.email,))
			if c.fetchone():
				return '''<font color='red'><b>×邮件地址已经存在！</b></font>'''
			else:
				return '''<font color='#4E7504'><b>√邮件地址可以使用</b></font>'''
		if i.dopost == 'register':
			#ip = web.ctx.ip
			salt = ''.join( random.sample('abcdefghijklmnopqrstuvwxyz',6) )
			md5 = hashlib.md5( i.password + salt ).hexdigest()
			ipv4 = util.str2ip(ip)
			try:
				c.execute('''insert into ac_upers 
					(username,salt,md5,nickname,email,date,ipv4)
					values (%s,%s,%s,%s,%s,%s,%s)''',
					(i.username.encode('utf-8'),salt,md5,i.nickname.encode('utf-8'),
					i.email,int(calendar.timegm(time.gmtime())),ipv4)							
				)
			except Exception as what:
				return util.error_page(u'''注册失败:%s'''%what.__str__().replace('"',"'"))
			return util.jump_page(u'注册成功，跳转首页中……','/')
		return util.error_page(u'少女傲娇中')

class apikey:
	def GET(self,arg):
		c = common.getdb().cursor()
		if arg == '':
			# check if you already have the api
			uid = web.cookies().get('uid')
			c.execute('select apikey from ac_apikeys where uid=%s',(uid,))
			x = c.fetchone()
			if x:
				apikey = x[0]
			else:
				apikey = ''
			html = tpls.get_template('apikey.html').render(cat="APIKEY",apikey=apikey)
			return html
		elif arg == 'apply':
			# no login no api
			uid = web.cookies().get('uid')
			md5 = web.cookies().get('md5')
			if uid and md5:
				c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
				x = c.fetchone()
				if x and x[0]==md5:
					c.execute('select apikey from ac_apikeys where uid=%s',(uid,))
					y = c.fetchone()
					if y:
						apikey = y[0]
						#return to normal page
						return util.jump_page(u'你已经有key了，再仔细找找……','/apikey/')
					else:
						#apply the key, and return to normal page
						apikey = md5 + hashlib.md5(md5).hexdigest()
						c.execute('replace into ac_apikeys (uid,apikey) values (%s,%s)',
							(int(uid),apikey) )
						return util.jump_page(u'申请成功，跳转apikey主页中……','/apikey/')
			return util.error_page(u'IP党没人权！登录去...','/login/')
		return util.error_page(u'少女傲娇中')

class banlist:
	def GET(self,arg):
		HOST = 'localhost'    # The remote host
		PORT = 1818         # The same port as used by the server
		s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
		s.connect((HOST, PORT))
		s.send('{"protocol":"banlist"}\n')
		data = s.recv(1024)
		s.close()
		j = json.loads(data)
		bl = []
		if not j.has_key("ok"): #not empty
			for k,v in j.items():
				try:
					ipstr = common.ip2str(int(k))
					due = common.int2timestr(int(v))
				except Exception as what:
					return what.__str__()
				bl.append((ipstr,due))
		html = ''
		try:
			html = tpls.get_template('banlist.html').render(cat=u"banlist",bl=bl)
		except Exception as what:
			return util.error_page(what.__str__())
		return html

class online:
	def GET(self,noarg):
		web.header('Content-Type', 'text/javascript')
		html = ''
		HOST = 'localhost'    # The remote host
		PORT = 1818         # The same port as used by the server
		try:
			s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
			s.connect((HOST, PORT))
			s.send('{"protocol":"online"}\n')
			data = s.recv(1024*32)
			s.close()
			j = json.loads(data)
		except Exception as what:
			return util.error_page(u'连接socket端口失败:%s'%what.__str__())
		if j.has_key("online"):
			try:
				c = common.getdb().cursor()
				num = len(j["online"])
				counter = defaultdict(int)
				for partid in j["online"]:
					counter[partid] += 1	
				ranks = sorted(counter.items(),key=itemgetter(1),reverse=True)
				ranks_with_title = []
				for r in ranks:
					partid = r[0]
					count = r[1]
					c.execute('select title from ac_threads where id=%s and visible=1',(int(float(partid)),))
					x = c.fetchone()	
					if x:
						title = x[0].decode("utf-8")[:18].replace("'",'"')
					else:
						title = u"未知"
						continue
					ranks_with_title.append([partid,count,title])
					if len(ranks_with_title) == 10:
						break
				html = tpls.get_template('online.html').render(cat=u'在线人数',num=num,ranks=ranks_with_title)
			except Exception as what:
				return util.error_page(u'生成在线页面失败'%what.__str__())
		else:
			num = 0
			ranks_with_title = []
			html = tpls.get_template('online.html').render(cat=u'在线人数',num=num,ranks=ranks_with_title)
		return html

class click:
	def GET(self,partid):
		try:
			ip = web.ctx.environ['HTTP_X_FORWARDED_FOR'] 
			ipv4 = util.str2ip(ip)
		except Exception as what:
			return repr(what)
		web.header('Content-Type', 'text/javascript')
		try:
			id = int(float(partid))
			c = common.getdb().cursor()
			c.execute('update ac_stats set avclicks = avclicks+1 where id=%s',(id,))
			c.execute('select clicks+avclicks from ac_stats where id=%s',(id,))
			clicks = c.fetchone()[0]
			c.execute('insert into ac_logs (ipv4,date,action,arg) values (%s,NOW(),%s,%s)',
				(ipv4,'click',id))
			return 'document.write("%s")' % clicks
		except Exception as what:
			return util.error_page(u'更新点击出错:%s'%what.__str__())
		return ''

class mark:
	def GET(self,id):
		try:
			id = int(id)
			referer = web.ctx.env.get('HTTP_REFERER')
			uid = web.cookies().get('uid')
			md5 = web.cookies().get('md5')
			if uid and md5:
				c = common.getdb().cursor()
				c.execute('select md5,nickname from ac_upers where uid=%s',int(uid))
				x = c.fetchone()
				if x and x[0]==md5:
					try:
						c.execute('select size,maxsize,ids,tags from acu_favorites where uid=%s',(int(uid),))
						size,maxsize,ids,tags = c.fetchone()
					except:
						size = 0
						maxsize = 100
						ids = ''
						tags = ''
						c.execute('insert into acu_favorites (uid,size,ids,tags) values (%s,0,"","")',(int(uid),))
					if size == maxsize:
						return util.error_page(u'以达到收藏个数上限',referer) 
					if str(id) in ids:
						return util.error_page(u'您已经收藏了本资源',referer)
					ids += '`%s' % str(id)
					tags += '`所有'
					c.execute('update acu_favorites set size=size+1, ids=%s, tags=%s where uid=%s',
								(ids,tags,int(uid)) )
					# 推送消息
					c.execute('select title from ac_threads where id=%s',(int(id),))
					title = c.fetchone()[0]
					c.execute('''insert into acu_feeds 
							(uid,type,arg,showmsg,url,urlname,date) values
							(%s,%s,%s,%s,%s,%s,NOW())''',
							(int(uid),'收藏',str(id),'',
							'/id/%s.001'%str(id),title) 
					)
					return util.jump_page(u'收藏成功',referer)
		except Exception as what:
			return util.error_page(u'收藏失败:%s'%what.__str__().replace('"',"'"))
		return util.jump_page(u'少女傲娇中',referer)

class userrank:
	def GET(self,arg):
		c = common.getdb().cursor()
		if arg == '':
			curpage = 1
			order = 'clicks'
			orderstr = 'clicks+avclicks'
			filename = PATH + '/data/userrank/%s/%s.html' % (order,str(curpage))
			if os.path.exists(filename):
				return open(filename,'rb').read()
		else:
			curpage = int(arg[-1])
			order = arg.split('/',1)[0]
			if order == 'clicks':
				orderstr = 'sum(clicks+avclicks)'
			elif order == 'comments':
				orderstr = 'sum(comments+avcomments)'
			elif order == 'subs':
				orderstr = 'sum(ac_stats.subs)'
			elif order == 'marks':
				orderstr = 'sum(marks)'
			elif order == 'count':
				orderstr = 'count(*)'
		try:
			c.execute('''select uid,nickname,count(uid),sum(clicks+avclicks),
				sum(comments+avcomments),sum(ac_stats.subs),sum(marks) 
				from (ac_threads left join ac_stats using (id))
						left join ac_upers using (uid)
				group by (uid) order by %s desc limit %d,%d''' % 
				(orderstr,(curpage-1)*common.USERRANK_PERPAGE,common.USERRANK_PERPAGE))
			ud = []
			c2 = common.getdb().cursor()
			c3 = common.getdb().cursor()
			for x in c.fetchall():
				c2.execute('''select id,title,osite
					from ac_threads left join ac_stats using (id)
					where uid = %s order by clicks desc limit 1''',(x[0],))
				id,title,osite = c2.fetchone()
				title = title.decode('utf-8')[:20]
				c3.execute('''select date from ac_threads where uid=%s 
					order by date desc limit 1''',(x[0],))
				date = common.int2timestr(c3.fetchone()[0])
				ud.append([ x[0],u'@'+x[1].decode('utf-8'),id,title,osite,date,x[2],x[3],x[4],x[5],x[6] ])
			start = (curpage-1)*common.USERRANK_PERPAGE
			cur,records,pages,navs,prev,next,last = util.generate_navs(curpage,common.USERRANK_TOTAL,common.USERRANK_PERPAGE)
			html = tpls.get_template('userrank.html').render(cat=u'名人堂',cur=cur,records=records,pages=pages,navs=navs,prev=prev,next=next,last=last,ud=ud,start=start,order=order)
			filename = PATH + '/data/userrank/%s/%s.html' % (order,str(curpage))
			common.ensure_dir(filename)
			open(filename,'w').write(html)
			return html			
		except Exception as what:
			return util.error_page(u'渲染失败:%s'%what.__str__().replace('"',"'"))
		return util.error_page(u'少女傲娇中')

class review:
	def POST(self,arg):
		i = web.input(id=None,score=None,action=None)
		if not i.score:
			score = 8;
		else:
			score = int(i.score)
		if not i.id or i.id=='0':
			return 'no id'
		else:
			id = int(float(i.id))
		c = common.getdb().cursor()
		try:
			uid = getuid(c=c)
			if not uid:
				return 'not logged in'
			#initialize if necessary
			c.execute('select status from ac_reviewstatus where id=%s',(id,))
			m = c.fetchone()
			if m:
				status = m[0]
			else:
				status = 'inreview'
				c.execute('insert into ac_reviewstatus values (%s,%s)',(id,status))
			c.execute('select * from ac_reviews where id=%s and uid=%s',(id,uid))
			m = c.fetchone()
			if not m:
				c.execute('insert into ac_reviews values (%s,%s,%s,%s,%s)',(id,8,0,uid,''))
			# if action
			review = ''
			if i.action:
				c.execute('select mask from ac_upers where uid=%s',(uid,))
				mask = c.fetchone()[0]
				if not(mask & common.UP_SUPER):
					return 'not admin'
				if i.action == "approve":
					status = "approved"
					score = 16
				else:
					status = "rejected"
					score = 0
				c.execute('replace into ac_reviewstatus values (%s,%s)',(id,status))
				review = i.review.encode('utf-8')
			# factor & adjscore
			factor = 0.0
			c.execute('''select count(*) from ac_threads where uid=%s and visible=1''',(uid,))
			factor += c.fetchone()[0]*5
			c.execute('''select posts from ac_upers where uid=%s''',(uid,))
			factor += c.fetchone()[0] / 10.
			adjscore = (score-8)/8.*factor
			# update
			if i.action:
				c.execute('''update ac_reviews set score=%s,adjscore=%s,review=%s 
					where id=%s and uid=%s''',(score,adjscore,review,id,uid))
			else:	
				c.execute('''update ac_reviews set score=%s,adjscore=%s
					where id=%s and uid=%s''',(score,adjscore,id,uid))
			# generate totalscore
			c.execute('''select sum(adjscore) from ac_reviews where id=%s''',(id,))
			m = c.fetchone()
			if m:
				totalscore = m[0]
			else:
				totalscore = 0
			if totalscore >= 20 and status=="inreview":
				status = "approved"
			#review
			c.execute('''select review from ac_reviews where id=%s''',(id,))
			for x in c.fetchall():
				if x[0]:
					review = x[0]
			rtn = {'status':status,'factor':factor,'adjscore':adjscore,'totalscore':totalscore,'review':review}
			return json.dumps(rtn)
		except Exception as what:
			return u'出错了:%s'%repr(what).replace('"',"'")

class checkpri:
	def GET(self,arg):
		uid = web.cookies().get('uid')
		try:
			if uid:
				uid = int(uid)
				c = common.getdb().cursor()
				factor = 0
				c.execute('''select count(*) from ac_threads where uid=%s and visible=1''',(uid,))
				factor += c.fetchone()[0]*5
				c.execute('''select posts from ac_upers where uid=%s''',(uid,))
				factor += c.fetchone()[0] / 10.
				c.execute('select mask from ac_upers where uid=%s',(uid,))
				mask = c.fetchone()[0]
				return str(factor+mask)
			else:
				return '0'
		except:
			return '0'

class admin:
	def GET(self,arg):
		return util.error_page(u'少女傲娇中')

#application = app.wsgifunc()
if __name__ == '__main__':
#	web.wsgi.runwsgi = lambda func, addr=None: web.wsgi.runfcgi(func, addr)
	app.run()
